/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.eisti.icc.zk;

import fr.eisti.icc.client.ClientBibliotheque;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import fr.eisti.icc.data.Emprunt;
import fr.eisti.icc.data.Emprunteur;
import fr.eisti.icc.data.Reservation;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JCheckBox;
import javax.xml.ws.Response;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.ext.AfterCompose;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Window;

/**
 *
 * @author clion
 */
public class ListEmprunts extends Tabbox implements AfterCompose {

    private Listbox listboxEmprunts;
    private Listbox listboxReservations;
    public static Session session;

    public void afterCompose() {
        Components.wireVariables(this, this);
        Components.addForwards(this, this);
        boolean isAdmin = Boolean.parseBoolean(session.getAttribute("admin") + "");
        HeaderListPrets(isAdmin);
        HeaderListReservations(isAdmin);
        init(listboxEmprunts, listboxReservations);

    }

    public static void addEmpruntInTheView(final Listbox listboxEmprunts, final Listbox listboxReservations, final Emprunt em, boolean isAdmin, final ClientBibliotheque cl) throws NumberFormatException {
        String strdateDebut = em.getDateDebutEmprunt();
        final Listitem l = new Listitem();
        Listcell l0 = new Listcell(em.getEmprunteur());
        Listcell l1 = new Listcell(em.getDocument().getTitre());
        Listcell l2 = new Listcell(strdateDebut);
        int annee = Integer.parseInt(strdateDebut.substring(6, 10));
        int mois = Integer.parseInt(strdateDebut.substring(3, 5)) - 1;
        int jour = Integer.parseInt(strdateDebut.substring(0, 2));
        GregorianCalendar dateFin = new GregorianCalendar(annee, mois, jour);
        Date today = new Date();

        // Get msec from each, and subtract.
        //Messagebox.show(em.getJours()+"");
        int diff = (int) ((dateFin.getTime().getTime() - today.getTime()) / (1000 * 60 * 60 * 24)) + em.getJours();
        Listcell l3 = new Listcell("" + diff + " j");
        if (isAdmin) {
            l.appendChild(l0);
        }
        l.appendChild(l1);
        l.appendChild(l2);
        l.appendChild(l3);

        if (isAdmin) {
            Listcell l4 = new Listcell();
            Button b = new Button();
            b.setLabel("<-|");
            b.addEventListener("onClick", new EventListener() {
                public void onEvent(Event event) throws Exception {
                    ClientResponse r = cl.recupererDocument_XML(em.getDocument().getId() + "", em.getEmprunteur());
                    if (r.getStatus() == 200) {
                        refresh(listboxEmprunts, listboxReservations);
                    } else {
                        Messagebox.show(r.toString());
                    }


                }
            });
            // b.setAction("onClick : Messagebox.show('rftgrfdg') ");

            //Attribute("label", "ereertret");
            // b.setAttribute("onClick", "Messagebox.show('rftgrfdg')");

            l4.appendChild(b);


            l.appendChild(l4);
            if (diff < 0) {
                l.setStyle("backgsround-color: #F8E7E8; text-align: center;");
            } else {
                l.setStyle("background-color: #CAF4D3; text-align: center;");
            }

        }
        listboxEmprunts.appendChild(l);
        listboxEmprunts.invalidate();
    }

    public void HeaderListPrets(boolean isAdmin) {
        Listhead head = new Listhead();
        head.setStyle("text-align: center;");
        Listheader h0 = new Listheader("Emprunteur");
        Listheader h1 = new Listheader("Livre");
        Listheader h2 = new Listheader("Date d'emprunts");
        Listheader h3 = new Listheader("Temps restant");
        Listheader h4 = new Listheader("Recuperer");
        if (isAdmin) {
            head.appendChild(h0);
        }
        head.appendChild(h1);
        head.appendChild(h2);
        head.appendChild(h3);
        if (isAdmin) {
            head.appendChild(h4);
        }

        listboxEmprunts.appendChild(head);
    }

    public void HeaderListReservations(boolean isAdmin) {
        Listhead head2 = new Listhead();
        head2.setStyle("text-align: center;");
        Listheader hr0 = new Listheader("Emprunteur");
        Listheader hr1 = new Listheader("Titre");
        Listheader hr2 = new Listheader("Date de demande");
        Listheader hr3 = new Listheader("Livre disponible");
        Listheader hr4 = new Listheader("Annuler");
        Listheader hr5 = new Listheader("Preter");
        if (isAdmin) {
            head2.appendChild(hr0);
        }
        head2.appendChild(hr1);
        head2.appendChild(hr2);
        head2.appendChild(hr3);
        head2.appendChild(hr4);
        if (isAdmin) {
            head2.appendChild(hr5);
        }
        listboxReservations.appendChild(head2);
    }

    public static void AddReservationInListView(final Listbox listboxEmprunts, final Listbox listboxReservations, final Reservation re, final ClientBibliotheque cl, boolean isAdmin) {
        String strdateDebut = re.getDateDemandeReservation();
        final Listitem l = new Listitem();
        Listcell l0 = new Listcell(re.getEmprunteur());
        Listcell l1 = new Listcell(re.getDocument().getTitre());
        Listcell l2 = new Listcell(strdateDebut);
        Listcell l3 = new Listcell(re.getDocument().isEstDisponible() ? "Oui" : "Non");
        Listcell l4 = new Listcell();
        Button b = new Button();
        b.setLabel("X");
        b.addEventListener("onClick", new EventListener() {
            public void onEvent(Event event) throws Exception {
                ClientResponse r = cl.annulerReservation_XML(re.getDocument().getId() + "");
                if (r.getStatus() == 200) {
                    refresh(listboxEmprunts, listboxReservations);

                } else {
                    Messagebox.show(r.toString());
                }


            }
        });
        l4.appendChild(b);
        if (!re.getDocument().isEstDisponible()) {
            l.setStyle("background-color: #F8E7E8; text-align: center;");
        } else {
            l.setStyle("background-color: #CAF4D3; text-align: center;");
        }
        if (isAdmin) {
            l.appendChild(l0);
        }
        l.appendChild(l1);
        l.appendChild(l2);
        l.appendChild(l3);
        l.appendChild(l4);
        if (isAdmin) {
            Listcell l5 = new Listcell();
            Button b2 = new Button();
            b2.setLabel("<-|");
            b2.addEventListener("onClick", new EventListener() {
                public void onEvent(Event event) throws Exception {



                    Map dataProfil = new HashMap();
                    dataProfil.put("loginEmprunteur", re.getEmprunteur());
                    dataProfil.put("documentAPreter", re.getDocument().getId());
                    dataProfil.put("duree",  cl.getClientByLogin_XML(Emprunteur.class, re.getEmprunteur()).getDureeMaxEmprunt());
                    dataProfil.put("cheque", "false");


                    Window window = (Window) Executions.createComponents(
                            "creerEmprunt.zul", null, dataProfil);
                    window.doModal();



//                    
//                    ClientResponse r = cl.annulerReservation_XML(re.getDocument().getId() + "");
//                    if (r.getStatus() == 200) {
//                        r = cl.preterDocument_XML(re.getDocument().getId() + "", re.getEmprunteur(), "false");
//                        
//                        if (r.getStatus() == 200) {
//                        } else {
//                           Messagebox.show(r.toString());
//                        }
//
//
//                    } else {
//                        Messagebox.show(r.toString());
//                    }
//                    refresh();


                }
            });
            l5.appendChild(b2);
            l.appendChild(l5);
        }
        listboxReservations.appendChild(l);
        listboxReservations.invalidate();
    }

    public static void init(Listbox listboxEmprunts, Listbox listboxReservations) throws NumberFormatException, UniformInterfaceException {
        session = Executions.getCurrent().getSession();
        boolean isAdmin = Boolean.parseBoolean(session.getAttribute("admin") + "");
        final ClientBibliotheque cl = new ClientBibliotheque();




        List<Emprunt> prests = cl.getListePrets_XML();
        for (final Emprunt em : prests) {
            addEmpruntInTheView(listboxEmprunts, listboxReservations, em, isAdmin, cl);
        }



        List<Reservation> reservations = cl.getListeReservation_XML();
        for (final Reservation re : reservations) {
            AddReservationInListView(listboxEmprunts, listboxReservations, re, cl, isAdmin);
        }
    }

    public static void refresh(Listbox listboxEmprunts, Listbox listboxReservations) throws UniformInterfaceException, NumberFormatException {

        //listboxEmprunts.detach();
        listboxEmprunts.getItems().clear();
        //listboxEmprunts.getHeads().clear();
        listboxReservations.getItems().clear();
        //listboxReservations.getHeads().clear();
        init(listboxEmprunts, listboxReservations);
        listboxEmprunts.invalidate();
        listboxReservations.invalidate();
    }
    
     public  void refresh() throws UniformInterfaceException, NumberFormatException {

      refresh(listboxEmprunts,listboxReservations);
    }
}
